package leetcode.customobject;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 要就O(1) 时间插入、删除和获取随机元素
 */
public class Program380RandomizedSet {

    //  思考数组怎么保证新增、删除O(1)
    private List<Integer> nums = new ArrayList<>();
    private Map<Integer, Integer> indices = new ConcurrentHashMap<>();
    private Random random = new Random();

    public Program380RandomizedSet() {

    }

    public boolean insert(int val) {
        if (indices.containsKey(val)) {
            return false;
        }
        int index = nums.size();
        nums.add(val);
        indices.put(val, index);
        return true;
    }

    public boolean remove(int val) {
        if (!indices.containsKey(val)) {
            return false;
        }
        int index = indices.get(val);
        int size = nums.size();
        if (index != size - 1) {
            // 没有顺序，直接替换最后一个
            int lastNum = nums.get(size - 1);
            nums.set(index, lastNum);
            indices.put(lastNum, index);
        }
        indices.remove(val);
        nums.remove(size - 1);
        return true;
    }

    public int getRandom() {
        int i = random.nextInt(nums.size());
        return nums.get(i);
    }

    public static void main(String[] args) {
        Program380RandomizedSet obj = new Program380RandomizedSet();
        System.out.println(obj.insert(3));
        System.out.println(obj.insert(-2));
        System.out.println(obj.remove(2));
        System.out.println(obj.insert(2));
        System.out.println(obj.getRandom());
        System.out.println(obj.remove(1));
        System.out.println(obj.insert(2));
        System.out.println(obj.getRandom());
    }
}
